package com.system.pay.service.impl;

import com.alipay.api.AlipayApiException;
import com.system.pay.bean.PayBean;
import com.system.pay.dto.QueryDTO;
import com.system.pay.dto.RefundDTO;
import com.system.pay.feign.AppointmentServiceFeign;
import com.system.pay.service.PayService;
import com.system.pay.utils.Alipay;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @className: AliPayServiceImpl
 * @description: 具体实现类，观察者模式
 * @author: Li Chuanwei
 * @date: 2023/12/03 9:15
 * @Company: Copyright [日期] by [作者或个人]
 **/

@Service
public class AliPayServiceImpl implements PayService {
    @Resource
    private Alipay alipay;

    @Autowired
    private AppointmentServiceFeign appointmentServiceFeign;

    @Override
    public String Pay(PayBean payBean) throws AlipayApiException {
        return alipay.pay((PayBean) payBean);
    }

    @Override
    public boolean paynotify(Map<String, String> receiveMap) throws Exception {
        boolean signVerified = alipay.signVerified(receiveMap);
        if (signVerified) {
            String tradeStatus = receiveMap.get("trade_status");
            if ("TRADE_FINISHED".equals(tradeStatus)
                    || "TRADE_SUCCESS".equals(tradeStatus)) {
                String orderNoStr = receiveMap.get("out_trade_no").toString();
                //将订单状态设置为已支付的状态
            }
        }
        return false;
    }

    @Override
    public Integer getResult(String out_trade_no) throws Exception {
        //订单作为观察者，当支付成功后，将订单状态设置为已支付的状态，支付结果作为被观察者
        String result = alipay.getResult(out_trade_no);
        if(result == null)
            return -1;
        if(result.contains("TRADE_FINISHED") || result.contains("TRADE_SUCCESS")){
            return appointmentServiceFeign.paySuccess(new QueryDTO(out_trade_no));
        }
        else
            return -1;
    }

    @Override
    public boolean appointmentRefund(RefundDTO refundDTO) throws AlipayApiException {
        return alipay.refund(refundDTO);
    }
}
